from src.core.Proxy import CallerProxy, DataFrameProxy
from src.core.Commander import Commander, MethodCall, Statement
import json
from src.helper.utils import CanJson, json_converter
from src.dataModel.pandasCmd import ColumnInfo, Field, PandasCmd
import pandas as pd
import pathlib


def json2file(obj, path, base='model_jsons'):
    path = pathlib.Path(base) / path
    with open(path, 'w') as f:
        json.dump(obj, indent=2, fp=f, default=json_converter)


def to_Commander():

    with Commander('test') as cmd:
        st = cmd.create_statement('df', 'ret')
        st.query('name1 is in [1,2,3,3]')

        json2file(cmd, 'Commander.json')


to_Commander()


def to_pandas_cmd_model():
    df = pd.DataFrame({
        'name': 'x1 x2 x3 x4'.split(),
        'n1': [1, 2, 3, 4],
        'n2': [1, 2, 3, 4],
    })

    cmd = PandasCmd.from_df(df)

    json2file(cmd, 'PandasCmdModel.json')


to_pandas_cmd_model()


def to_pandas_cmd_mulcols_model():
    df = pd.DataFrame({
        'name': 'x1 x2 x3 x4'.split(),
        'n1': [1, 2, 3, 4],
        'n2': [1, 2, 3, 4],
    }).groupby('name').agg({'n1': [sum, 'mean'], 'n2': sum})

    cmd = PandasCmd.from_df(df)
    json2file(cmd, 'PandasCmdModel_mulcols.json')


to_pandas_cmd_mulcols_model()


def to_commanders_model():
    df = pd.DataFrame({
        'name': 'x1 x2 x3 x4'.split(),
        'n1': [1, 2, 3, 4],
        'n2': [1, 2, 3, 4],
    })

    df_px = CallerProxy()
    df_px.set_obj_to_var('df', df)

    with df_px.with_cmd('步骤1') as cmd:
        cmd.create_statement('df', 'query_res')
        df_px.query('name=="x1"')

        cmd.create_statement('df', 'gp_res')
        df_px.groupby('name')
        df_px.agg({'n1': [sum, 'mean'], 'n2': sum})

    with df_px.with_cmd('步骤2') as cmd:
        cmd.create_statement('df', 'query_res')
        df_px.query('name=="x1"')

    json2file(list(df_px.cmdManager.get_cmds()), 'commandersModel.json')


to_commanders_model()
